package com.lucky.common.util;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtil {
	/**
	 * 首字母大写
	 * 
	 * @param src
	 * @return
	 */
	public static String toFirstUppercase(String src) {
		byte[] ss = src.getBytes();
		if (ss[0] >= 97 && ss[0] <= 122) {
			ss[0] = (byte) (ss[0] - 32);
			return new String(ss);
		}
		return src;
	}
	/**
	 * 验证字母下划线（中间允许空格）
	 * */
	public static boolean checkStringToAlphUnderLine(String str) {
		if(str==null||"".equals(str)) {
			return false;
		}else {
			str=str.trim();
		}
		if(!str.contains(" ")) {
			return str.matches("^[a-zA-Z_]+(\\s*[a-zA-Z_\\.]+)*$");
		}
		return str.matches("^[a-zA-Z_]+(\\s*[a-zA-Z_\\.]+)*$")&&checkRisk(str);
	}
	
	
	/**
	 * 验证字母下划线（中间允许空格）
	 * */
	public static boolean checkStringToAlphNumUnderLine(String str) {
		if(str==null||"".equals(str)) {
			return false;
		}else {
			str=str.trim();
		}
		if(!str.contains(" ")) {
			return str.matches("^[0-9a-zA-Z_]+(\\s*[0-9a-zA-Z_\\.]+)*$");
		}
		return str.matches("^[0-9a-zA-Z_]+(\\s*[0-9a-zA-Z_\\.]+)*$")&&checkRisk(str);
	}

	
	/**
	 * 验证尖括号（中间允许空格）
	 * */
	public static String checkStringToCracket(String str) {
		if(str==null||"".equals(str)) {
			return "0";
		}else {
			str=str.trim();
		}
		if("<>".contains(str)) {
			if("<".equals(str)) {
				return "left";
			}else if(">".equals(str)){
				return "right";
			}else {
				return "0";
			}
		}else {
			return "0";
		}
	}
	
	
	private static boolean checkRisk(String str) {

		// 转换成小写
        str = str.toLowerCase();

        // 非法字符
        String[] keywords = { "master", "truncate", "insert", "select", "delete", "update", "declare", "alert",
                "create", "drop","xp_cmdshell"};
        // 判断是否包含非法字符
        for (String keyword : keywords) {
            if (str.contains(keyword)) {
            	return false;
            }
        }
		return true;
		
	}
	
	/**
	 * 验证数字（可含零到多个英文逗号）
	 * */
	public static boolean checkStringToNumAlph(String str) {
		if(str==null||"".equals(str.trim())) {
			return false;
		}else {
			str=str.replace(" ", "");
//			//去掉单引号
//			str=str.replace("'", "");
//			//去掉逗号
//			str=str.replace(",", "");
		}
		return str.matches("^[0-9a-zA-Z_\\',]*$")&&checkRisk(str);
	}
	
	/**
	 * 验证数字（可含零到多个英文逗号）
	 * */
	public static boolean checkStringToNum(String str) {
		if(str==null||"".equals(str.trim())) {
			return false;
		}else {
			str=str.replace(" ", "");
//			//去掉单引号
//			str=str.replace("'", "");
//			//去掉逗号
//			str=str.replace(",", "");
		}
		//return str.matches("^\\d+(,\\d+)*$|^\\'\\d+\\'(,\\'\\d+\\')*$");
		return str.matches("^[0-9\\',]*$");
	}
	
 
	
	/**
	 * 首字母小写
	 * 
	 * @param src
	 * @return
	 */
	public static String toFirstLowerCase(String src) {
		byte[] ss = src.getBytes();
		if (ss[0] >= 65 && ss[0] <= 90) {
			ss[0] = (byte) (ss[0] + 32);
			return new String(ss);
		}
		return src;
	}

	/**
	 * 字符串转日期
	 * 
	 * @param str
	 * @param type
	 *            如 yyyy-MM-dd HH:mm:ss等
	 * @return
	 * @throws ParseException
	 */
	public static Date stringToDate(String str, String type) throws ParseException {
		if(str==null||"".equals(str.trim())){
			return null;
		}else{
			SimpleDateFormat sdf = new SimpleDateFormat(type);
			//sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
			Date date = sdf.parse(str);
			return date;
		}
	}
	/**
	 * 严格时间校验 闰年不会自动转
	 * @param str
	 * @param type
	 * @return
	 * @throws ParseException
	 */
	public static Date stringToDateLenientFalse(String str, String type) throws ParseException {
		if(str==null||"".equals(str.trim())){
			return null;
		}else{
			SimpleDateFormat sdf = new SimpleDateFormat(type);
			sdf.setLenient(false);
			Date date = sdf.parse(str);
			return date;
		}
	}
	

	/**
	 * 日期转字符串
	 * 
	 * @param date
	 * @param type
	 *            如 yyyy-MM-dd HH:mm:ss等
	 * @return
	 */
	public static String dateToString(Date date, String type) {
		
		if(date==null) return "";
		
		SimpleDateFormat sdf = new SimpleDateFormat(type);
		//sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
		String datestr = sdf.format(date);
		return datestr;
	}
	/**
	 * 
	 * 字符串转int
	 * @return 
	 */
	public static int StringToInt(String str) throws NumberFormatException {
		return Integer.parseInt(str);
	}
	
	/**
	 * 
	 * 查询条件判空
	 * @return 
	 */
	public static boolean ConditionIsNull(String str) {
		return str!=null&&!"".equals(str.trim());
	}
	
	public static boolean isInteger(String str){
		boolean isInteger = false;
		try{
			new Integer(str);
			isInteger = true;
		}catch(Exception ex){
			
		}
		return isInteger;
	}
	
	public static boolean isLong(String str){
		boolean isLong = false;
		try{
			new Long(str);
			isLong = true;
		}catch(Exception ex){
			
		}
		return isLong;
	}
	
	/**
	 * 替换不规则路径分隔符
	 * @param path
	 * @return
	 */
	public static String getFilepath(String path)
	{
		if(path==null||"".equals(path))
		{
			return "";
		}
		else
		{
			if(path.indexOf("//")!=-1)
			{
				path = path.replaceAll("//","/");// 替换 //
			}
			if(path.indexOf("\\")!=-1)
			{
				path = path.replaceAll("\\\\\\\\","/");// 替换 \\
			}			
			path = path.replaceAll("\\\\","/");	// 替换 \							
		}
		return path;
	}
	
	public static String get12Random(){
		String ranStr = "0123456789";
		Random ran = new Random();
		StringBuffer sbf = new StringBuffer();
		for(int i=0;i<12;i++){
			char c = ranStr.charAt(ran.nextInt(10));
			sbf.append(c);
		}
		
		return sbf.toString();
	}
	
	/**
	 * 驼峰格式转下划线方式
	 * @param str
	 * @return
	 */
	public static String trans(String str){
        
        List record =new ArrayList();
        for(int i=0;i<str.length();i++)
        {
            char tmp =str.charAt(i);
             
            if((tmp<='Z')&&(tmp>='A'))
            {
                record.add(i);//记录每个大写字母的位置
            }
             
        }
//        record.remove(0);//不需要加下划线设置
         
        str= str.toLowerCase();
        char[] charofstr = str.toCharArray();
        String[] t =new String[record.size()];
        for(int i=0;i<record.size();i++)
        {
            t[i]="_"+charofstr[Integer.parseInt(record.get(i)+"")];//加“_”
        }
        String result ="";
        int flag=0;
        for(int i=0;i<str.length();i++)
        {
            if((flag<record.size())&&(i==Integer.parseInt(record.get(flag)+""))){
                result+=t[flag];
                flag++;
            }
            else
                result+=charofstr[i];
        }
         
        return result;
    }
	
	/** 
     * 下划线转换为驼峰 
     *  
     * @param underscoreName 
     * @return 
     */  
    public static String camelCaseName(String underscoreName) { 
    	underscoreName = underscoreName.toLowerCase();
        StringBuilder result = new StringBuilder();  
        if (underscoreName != null && underscoreName.length() > 0) {  
            boolean flag = false;  
            for (int i = 0; i < underscoreName.length(); i++) {  
                char ch = underscoreName.charAt(i);  
                if ("_".charAt(0) == ch) {  
                    flag = true;  
                } else {  
                    if (flag) {  
                        result.append(Character.toUpperCase(ch));  
                        flag = false;  
                    } else {  
                        result.append(ch);  
                    }  
                }  
            }  
        }  
        return result.toString();  
    }  
	
	/**
	 * 去掉换行空格tab等
	 * @param str
	 * @return
	 */
	public static String replaceBlank(String str) {
        String dest = "";
        if (str!=null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }
	
	/**
	 * 防止报错的补充方法，由com.rfp.gpp.core.util.getOrderIDArr1(String strIDs,String numStr)平移而来
	 * @param strIDs
	 * @param numStr
	 * @return
	 */
	public static List<String> getOrderIDArr1(String strIDs,String numStr) {

        int num = Integer.valueOf(numStr);
        List<String> idArr = new ArrayList<String>();

        while (strIDs.split(",").length>num || strIDs.length() > 2000) {
            if(strIDs.length()>2000){
                for (int i = 2000; i > 0; i--) {
                    if (",".equals(strIDs.charAt(i - 1) + "")) {
                        String temp = strIDs.substring(0, i - 1);
                        String[] str = temp.split(",");
                        if(str.length<=num){
                            idArr.add(temp);
                            strIDs = strIDs.substring(i);
                            break;
                        }
                    }
                }
            }else{
                for (int i = strIDs.length(); i > 0; i--) {
                    if (",".equals(strIDs.charAt(i - 1) + "")) {
                        String temp = strIDs.substring(0, i - 1);
                        String[] str = temp.split(",");
                        if(str.length<=num){
                            idArr.add(temp);
                            strIDs = strIDs.substring(i);
                            break;
                        }
                    }
                }
            }

        }
        idArr.add(strIDs);

        return idArr;
    }

	/**
	 * 判断字符串中，包含了几个指定的字符
	 * @return
	 */

		public static int countSubstring(String original, String toCount) {
			int count = 0;
			int index = 0;
			while ((index = original.indexOf(toCount, index)) != -1) {
				count++;
				index += toCount.length(); // 移动到下一个字符，避免重复计数
			}
			return count;
		}

		
	public static String null2Blank(Object o) {
		return o==null?"":String.valueOf(o);
	}
}
